package com.lw.leetcode.back;

import java.util.ArrayList;
import java.util.List;

/**
 * 216. 组合总和 III
 *
 * @Author liw
 * @Date 2021/4/30 14:48
 * @Version 1.0
 */
public class CombinationSum3 {

    public static void main(String[] args) {
        CombinationSum3 test = new CombinationSum3();
        List<List<Integer>> lists = test.combinationSum3(9, 45);
        System.out.println(lists);
    }

    public List<List<Integer>> combinationSum3(int k, int n) {

        List<List<Integer>> all = new ArrayList<>();
        List<Integer> list = new ArrayList<>();

        combinationSum3(k, n, 0, 0, all, list);
        return all;
    }

    public static boolean combinationSum3(int k, int n, int count, int sum, List<List<Integer>> all, List<Integer> list) {
        if (k == count) {
            if (n != sum) {
                return n > sum;
            }
            all.add(new ArrayList<>(list));
        }
        if (n < sum) {
            return false;
        }
        int size = list.size();
        int st = size == 0 ? 1 : list.get(size - 1) + 1;
        for (int i = st; i <= 9; i++) {
            list.add(i);
            boolean b = combinationSum3(k, n, count + 1, sum + i, all, list);
            list.remove(size);
            if (!b) {
                break;
            }
        }
        return true;
    }
}
